using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos.DrugManagement;
using Work.Domain.DrugManage;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 获取药品列表处理器（用于药品查看模块）
    /// </summary>
    public class GetDrugsQueryHandler : IRequestHandler<GetDrugsQuery, ApiResult<List<DrugDto>>>
    {
        private readonly IBaseRepository<Drug> _drugRepo;
        private readonly IMapper _mapper;

        public GetDrugsQueryHandler(IBaseRepository<Drug> drugRepo, IMapper mapper)
        {
            _drugRepo = drugRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<DrugDto>>> Handle(GetDrugsQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<DrugDto>>();

            try
            {
                var query = _drugRepo.GetAll().AsNoTracking();

                // 动态构建查询条件
                if (!string.IsNullOrWhiteSpace(request.DrugName))
                {
                    query = query.Where(d => d.DrugName.Contains(request.DrugName));
                }

                if (!string.IsNullOrWhiteSpace(request.DrugType))
                {
                    query = query.Where(d => d.DrugType == request.DrugType);
                }

                if (!string.IsNullOrWhiteSpace(request.CostName))
                {
                    query = query.Where(d => d.CostName == request.CostName);
                }

                if (!string.IsNullOrWhiteSpace(request.DosageForm))
                {
                    query = query.Where(d => d.DosageForm == request.DosageForm);
                }

                if (!string.IsNullOrWhiteSpace(request.Specification))
                {
                    query = query.Where(d => d.Specification == request.Specification);
                }

                if (request.MinPurchasePrice.HasValue)
                {
                    query = query.Where(d => d.PurchasePrice >= request.MinPurchasePrice.Value);
                }

                if (request.MaxPurchasePrice.HasValue)
                {
                    query = query.Where(d => d.PurchasePrice <= request.MaxPurchasePrice.Value);
                }

                if (request.MinSellingPrice.HasValue)
                {
                    query = query.Where(d => d.SellingPrice >= request.MinSellingPrice.Value);
                }

                if (request.MaxSellingPrice.HasValue)
                {
                    query = query.Where(d => d.SellingPrice <= request.MaxSellingPrice.Value);
                }

                // 是否只显示启用的药品
                if (request.OnlyEnabled)
                {
                    query = query.Where(d => d.IsEnabled);
                }

                // 按药品名称排序
                var drugs = await query
                    .OrderBy(d => d.DrugName)
                    .ToListAsync(cancellationToken);

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = _mapper.Map<List<DrugDto>>(drugs);
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<DrugDto>();
            }

            return result;
        }
    }
}

